<template>
  <el-dialog title="权限设置" class="rounded-[15px]" v-model="show" @opened="setKeys">
    <el-scrollbar height="550px">
      <el-tree
        :indent="30"
        :data="props!.data"
        show-checkbox
        :check-on-click-node="true"
        ref="treeRef"
        node-key="count"
        :check-strictly="true"
      >
        <template #default="{ data }">
          <div>{{ data.name }}({{ data.type === "route" ? "页面" : "资源" }})</div>
        </template>
      </el-tree>
    </el-scrollbar>
    <template #footer>
      <el-button @click="confirm">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { ElMessage, ElTree } from "element-plus";
import { changePower } from "@/api/modules/role";

const treeRef = ref<InstanceType<typeof ElTree> | null>();

const show = ref(false);

interface Props {
  row: any;
  data?: any;
  select?: any;
  flat?: any;
  getTable?: () => Promise<any>;
}

const props = ref<Props>();

// 获取当前的选择的id
const counts = ref<number[]>([]);

const open = (params: Props) => {
  props.value = params;

  counts.value = props.value.select.map((e: any) => e.count);

  show.value = true;
};

// 设置keys
const setKeys = () => {
  treeRef.value?.setCheckedKeys(counts.value);
};

interface Power {
  role_id: number;
  routes: number[];
  apis: number[];
}

// 设置权限
const confirm = async () => {
  const power: Power = { role_id: props.value?.row.id, routes: [], apis: [] };
  const nowCounts = treeRef.value?.getCheckedKeys() as number[];
  console.log(nowCounts);
  for (let i = 0; i < nowCounts.length; i++) {
    const index = props.value?.flat.findIndex((e: any) => e.count === nowCounts[i]);
    if (index !== -1) {
      if (props.value?.flat[index].type === "route") {
        power.routes.push(props.value?.flat[index].id);
      } else if (props.value?.flat[index].type === "api") {
        power.apis.push(props.value?.flat[index].id);
      }
    }
  }

  try {
    await changePower(power);
    await props.value?.getTable!();
    ElMessage.success("成功!");
    show.value = false;
  } catch (error) {}
};

defineExpose({
  open
});
</script>

<style></style>
